using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Text;
using System.Windows.Forms;
using ctsu.Admin.BusLogic;

using ctsu.BaseForms;
using ctsu.Security;
using ctsu.Data;


namespace ctsu.Admin.Forms
{
	public class FormCoreLabQueryInventory : ctsu.BaseForms.FormBase2
	{
		#region members
		public event BusinessLogicEvents.BLGridViewEventHandler GridView;

		private FormMain _main;
		private FormInfoBase _formInfo;
		private Permission _formSecurity;
		private Hashtable _configData;
		private DataView _dataView;
		private DataTable _dataTable;

		FormGrid _fg;

		private bool _ignoreEvent;

		//printing
		private PrintDialog _pDlg;
		private PrintDocument _pDoc;
		private int _page;
		private int _startRow;
		private StringBuilder _criteria;
		private StringBuilder _resultsCriteria;

		#endregion members

		#region windows controls
		private System.Windows.Forms.Label label6;
		private System.Windows.Forms.ComboBox Patients;
		private System.Windows.Forms.Button btnRun;
		private System.Windows.Forms.Label label3;
		private System.Windows.Forms.ComboBox Tests;
		private System.Windows.Forms.Label label2;
		private System.Windows.Forms.Label label1;
		private System.Windows.Forms.CheckBox chkShowAll;
		private System.Windows.Forms.CheckBox chkFreezer;
		private System.Windows.Forms.CheckBox chkOutOther;
		private System.Windows.Forms.GroupBox gbxCriteria;
		private System.Windows.Forms.CheckBox chkCombine;
		private System.Windows.Forms.GroupBox groupBox1;
		private System.Windows.Forms.DataGrid dGrd;
		private System.Windows.Forms.CheckBox chkTesting;
		private System.Windows.Forms.ComboBox Protocols;
		private System.ComponentModel.IContainer components = null;
		#endregion windows controls

		#region initilaize
		public FormCoreLabQueryInventory(FormMain main, FormInfoBase fi, Permission formSecurity, Hashtable configData)
		{

			InitializeComponent();

			this._main = main;
			GridView += new ctsu.BaseForms.BusinessLogicEvents.BLGridViewEventHandler(main.OnGridView);
			this._formInfo = fi;
			this._formSecurity = formSecurity;
			this._configData = configData;
		}

		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		#region Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(FormCoreLabQueryInventory));
			this.label6 = new System.Windows.Forms.Label();
			this.Patients = new System.Windows.Forms.ComboBox();
			this.btnRun = new System.Windows.Forms.Button();
			this.label3 = new System.Windows.Forms.Label();
			this.Tests = new System.Windows.Forms.ComboBox();
			this.label2 = new System.Windows.Forms.Label();
			this.Protocols = new System.Windows.Forms.ComboBox();
			this.label1 = new System.Windows.Forms.Label();
			this.chkShowAll = new System.Windows.Forms.CheckBox();
			this.chkFreezer = new System.Windows.Forms.CheckBox();
			this.chkTesting = new System.Windows.Forms.CheckBox();
			this.chkOutOther = new System.Windows.Forms.CheckBox();
			this.dGrd = new System.Windows.Forms.DataGrid();
			this.gbxCriteria = new System.Windows.Forms.GroupBox();
			this.chkCombine = new System.Windows.Forms.CheckBox();
			this.groupBox1 = new System.Windows.Forms.GroupBox();
			this.pnl2.SuspendLayout();
			this.ButtonGroup.SuspendLayout();
			((System.ComponentModel.ISupportInitialize)(this.dGrd)).BeginInit();
			this.gbxCriteria.SuspendLayout();
			this.groupBox1.SuspendLayout();
			this.SuspendLayout();
			// 
			// pnl2
			// 
			this.pnl2.Controls.Add(this.groupBox1);
			this.pnl2.Controls.Add(this.gbxCriteria);
			this.pnl2.Controls.Add(this.dGrd);
			this.pnl2.Controls.Add(this.label1);
			this.pnl2.Name = "pnl2";
			this.pnl2.Size = new System.Drawing.Size(752, 456);
			// 
			// btnExit
			// 
			this.btnExit.Name = "btnExit";
			this.btnExit.Click += new System.EventHandler(this.btnExit_Click);
			// 
			// btnCancel
			// 
			this.btnCancel.Name = "btnCancel";
			this.btnCancel.Visible = false;
			// 
			// btnSave
			// 
			this.btnSave.Name = "btnSave";
			this.btnSave.Visible = false;
			// 
			// ButtonGroup
			// 
			this.ButtonGroup.Name = "ButtonGroup";
			this.ButtonGroup.Size = new System.Drawing.Size(760, 40);
			// 
			// btnPrint
			// 
			this.btnPrint.Name = "btnPrint";
			this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
			// 
			// btnGrid
			// 
			this.btnGrid.Name = "btnGrid";
			this.btnGrid.Click += new System.EventHandler(this.btnGrid_Click);
			// 
			// label6
			// 
			this.label6.Location = new System.Drawing.Point(336, 44);
			this.label6.Name = "label6";
			this.label6.Size = new System.Drawing.Size(72, 16);
			this.label6.TabIndex = 38;
			this.label6.Text = "Patient";
			// 
			// Patients
			// 
			this.Patients.Location = new System.Drawing.Point(336, 60);
			this.Patients.Name = "Patients";
			this.Patients.Size = new System.Drawing.Size(176, 21);
			this.Patients.TabIndex = 37;
			this.Patients.SelectedIndexChanged += new System.EventHandler(this.Patients_SelectedIndexChanged);
			// 
			// btnRun
			// 
			this.btnRun.Location = new System.Drawing.Point(432, 16);
			this.btnRun.Name = "btnRun";
			this.btnRun.TabIndex = 36;
			this.btnRun.Text = "Run Search";
			this.btnRun.Click += new System.EventHandler(this.btnRun_Click);
			// 
			// label3
			// 
			this.label3.Location = new System.Drawing.Point(144, 44);
			this.label3.Name = "label3";
			this.label3.Size = new System.Drawing.Size(88, 16);
			this.label3.TabIndex = 35;
			this.label3.Text = "Test Type";
			// 
			// Tests
			// 
			this.Tests.Location = new System.Drawing.Point(144, 60);
			this.Tests.Name = "Tests";
			this.Tests.Size = new System.Drawing.Size(176, 21);
			this.Tests.TabIndex = 34;
			this.Tests.SelectedIndexChanged += new System.EventHandler(this.Tests_SelectedIndexChanged);
			// 
			// label2
			// 
			this.label2.Location = new System.Drawing.Point(8, 44);
			this.label2.Name = "label2";
			this.label2.Size = new System.Drawing.Size(112, 16);
			this.label2.TabIndex = 33;
			this.label2.Text = "Protocol";
			// 
			// Protocols
			// 
			this.Protocols.Location = new System.Drawing.Point(8, 60);
			this.Protocols.Name = "Protocols";
			this.Protocols.Size = new System.Drawing.Size(121, 21);
			this.Protocols.TabIndex = 32;
			this.Protocols.SelectedIndexChanged += new System.EventHandler(this.Spids_SelectedIndexChanged);
			// 
			// label1
			// 
			this.label1.Location = new System.Drawing.Point(8, 112);
			this.label1.Name = "label1";
			this.label1.Size = new System.Drawing.Size(88, 16);
			this.label1.TabIndex = 31;
			this.label1.Text = "Search Criteria";
			// 
			// chkShowAll
			// 
			this.chkShowAll.Checked = true;
			this.chkShowAll.CheckState = System.Windows.Forms.CheckState.Checked;
			this.chkShowAll.Location = new System.Drawing.Point(8, 24);
			this.chkShowAll.Name = "chkShowAll";
			this.chkShowAll.Size = new System.Drawing.Size(80, 16);
			this.chkShowAll.TabIndex = 39;
			this.chkShowAll.Text = "Show All";
			this.chkShowAll.CheckedChanged += new System.EventHandler(this.chkShowAll_CheckedChanged);
			// 
			// chkFreezer
			// 
			this.chkFreezer.Location = new System.Drawing.Point(8, 56);
			this.chkFreezer.Name = "chkFreezer";
			this.chkFreezer.Size = new System.Drawing.Size(88, 16);
			this.chkFreezer.TabIndex = 40;
			this.chkFreezer.Text = "In Freezer ";
			this.chkFreezer.CheckedChanged += new System.EventHandler(this.chkOther_CheckedChanged);
			// 
			// chkTesting
			// 
			this.chkTesting.Location = new System.Drawing.Point(88, 24);
			this.chkTesting.Name = "chkTesting";
			this.chkTesting.Size = new System.Drawing.Size(112, 16);
			this.chkTesting.TabIndex = 41;
			this.chkTesting.Text = "Out For Testing";
			this.chkTesting.CheckedChanged += new System.EventHandler(this.chkOther_CheckedChanged);
			// 
			// chkOutOther
			// 
			this.chkOutOther.Location = new System.Drawing.Point(88, 56);
			this.chkOutOther.Name = "chkOutOther";
			this.chkOutOther.Size = new System.Drawing.Size(80, 16);
			this.chkOutOther.TabIndex = 42;
			this.chkOutOther.Text = "Out Other";
			this.chkOutOther.CheckedChanged += new System.EventHandler(this.chkOther_CheckedChanged);
			// 
			// dGrd
			// 
			this.dGrd.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
				| System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.dGrd.DataMember = "";
			this.dGrd.HeaderForeColor = System.Drawing.SystemColors.ControlText;
			this.dGrd.Location = new System.Drawing.Point(8, 128);
			this.dGrd.Name = "dGrd";
			this.dGrd.ReadOnly = true;
			this.dGrd.Size = new System.Drawing.Size(736, 320);
			this.dGrd.TabIndex = 43;
			// 
			// gbxCriteria
			// 
			this.gbxCriteria.Controls.Add(this.chkCombine);
			this.gbxCriteria.Controls.Add(this.btnRun);
			this.gbxCriteria.Controls.Add(this.label3);
			this.gbxCriteria.Controls.Add(this.Tests);
			this.gbxCriteria.Controls.Add(this.label2);
			this.gbxCriteria.Controls.Add(this.Patients);
			this.gbxCriteria.Controls.Add(this.Protocols);
			this.gbxCriteria.Controls.Add(this.label6);
			this.gbxCriteria.Location = new System.Drawing.Point(8, 8);
			this.gbxCriteria.Name = "gbxCriteria";
			this.gbxCriteria.Size = new System.Drawing.Size(520, 96);
			this.gbxCriteria.TabIndex = 44;
			this.gbxCriteria.TabStop = false;
			this.gbxCriteria.Text = "Search Criteria";
			// 
			// chkCombine
			// 
			this.chkCombine.Location = new System.Drawing.Point(8, 20);
			this.chkCombine.Name = "chkCombine";
			this.chkCombine.Size = new System.Drawing.Size(104, 16);
			this.chkCombine.TabIndex = 39;
			this.chkCombine.Text = "Combine";
			// 
			// groupBox1
			// 
			this.groupBox1.Controls.Add(this.chkShowAll);
			this.groupBox1.Controls.Add(this.chkOutOther);
			this.groupBox1.Controls.Add(this.chkTesting);
			this.groupBox1.Controls.Add(this.chkFreezer);
			this.groupBox1.Location = new System.Drawing.Point(536, 8);
			this.groupBox1.Name = "groupBox1";
			this.groupBox1.Size = new System.Drawing.Size(208, 80);
			this.groupBox1.TabIndex = 45;
			this.groupBox1.TabStop = false;
			this.groupBox1.Text = "Query Results Criteria";
			// 
			// FormCoreLabQueryInventory
			// 
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
			this.ClientSize = new System.Drawing.Size(760, 502);
			this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
			this.Name = "FormCoreLabQueryInventory";
			this.Text = "Core Lab - Query Inventory Screen";
			this.Resize += new System.EventHandler(this.FormCoreLabQueryInventory_Resize);
			this.Load += new System.EventHandler(this.FormCoreLabQueryInventory_Load);
			this.pnl2.ResumeLayout(false);
			this.ButtonGroup.ResumeLayout(false);
			((System.ComponentModel.ISupportInitialize)(this.dGrd)).EndInit();
			this.gbxCriteria.ResumeLayout(false);
			this.groupBox1.ResumeLayout(false);
			this.ResumeLayout(false);

		}
		#endregion


		private void FormCoreLabQueryInventory_Load(object sender, System.EventArgs e)
		{
			FillProtocolList();
			FillTestList();
			FillPatientList();
		}

		private void FormCoreLabQueryInventory_Resize(object sender, System.EventArgs e)
		{
			if (this.Height > 496)
				pnl2.Height = this.Height - 46;
			if (this.Width > 768)
				pnl2.Width = this.Width - 2;
		}

		private void FillProtocolList()
		{
			StringBuilder sb = new StringBuilder();
			string sql = "SELECT DISTINCT d.Protocol " +
				" FROM TestSamples t, DrawSamples d " +
				" WHERE t.DrawSample = d.ID ORDER BY d.Protocol";

			Protocols.BeginUpdate();
			Protocols.Text = "";

			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql);
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql);	

				Protocols.Items.Add("");
				while (reader.Read())
				{
					Protocols.Items.Add(reader.GetInt32(0).ToString());
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve protocols for Protocol List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Protocol List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Protocols.EndUpdate();
			}
		}

		private void FillTestList()
		{
			StringBuilder sb = new StringBuilder();
			StringBuilder sql = new StringBuilder();
			//int spid = 0;			

			Tests.BeginUpdate();
			Tests.Text = "";
			Tests.Items.Clear();

			sql.Append("SELECT DISTINCT tt.Display, t.TestType " +
				" From TestType_L tt, TestSamples t, DrawSamples d " +
				" WHERE t.DrawSample = d.ID " +
				" AND t.TestType = tt.ID ");

			Forms.NameVal nv = null;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql.ToString());				
				Tests.Items.Add(new NameVal(-1, ""));

				while (reader.Read())
				{
					nv = new NameVal(reader.GetInt32(1), reader.GetString(0));
					Tests.Items.Add(nv);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve tests for Test Type List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Test Type List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();
				Tests.EndUpdate();
			}
		}

		private void FillPatientList()
		{
			StringBuilder sb = new StringBuilder();
			StringBuilder sql = new StringBuilder();

			Patients.BeginUpdate();
			Patients.Text = "";
			Patients.Items.Clear();

			sql.Append("SELECT DISTINCT d.Patient " +
				" From TestSamples t, DrawSamples d " +
				" WHERE t.DrawSample = d.ID");

			PatientInfo pi = null;
			int id;
			string message = "";
			Forms.NameVal nv = null;
			//SqlConnection conn = LoginForm.GetSqlConnection();
			IDataReader reader = null;
			try
			{
				reader = DataAccess.GetDataReader(sql.ToString());
				//reader = SqlHelper.ExecuteReader(conn, CommandType.Text, sql.ToString());								
				Patients.Items.Add(new NameVal(-1, ""));

				while (reader.Read())
				{
					id = reader.GetInt32(0);
					message = "";
					pi = CoreLabUtils.GetPatientInfo(id, out message);
					nv = new NameVal(pi.ID, pi.GetNameOrIdentifier());
					Patients.Items.Add(nv);
				}
			}
			catch (Exception ex)
			{
				sb.Append("Could not retrieve patients for Patient List!");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				MessageBox.Show(this, sb.ToString(), "Fill Patient List Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
				return;
			}
			finally
			{
				if (reader != null)
				{
					if (!reader.IsClosed)
						reader.Close();
				}
				//if(conn != null)
				//    conn.Dispose();			
				Patients.EndUpdate();
			}
		}
		#endregion initilaize

		#region selectedIndexChanged
		private void Spids_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (chkCombine.Checked)
				return;
			if (_ignoreEvent)
				return;

			_ignoreEvent = true;
			Tests.Text = "";
			Patients.Text = "";
			_ignoreEvent = false;
		}

		private void Tests_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (chkCombine.Checked)
				return;
			if (_ignoreEvent)
				return;

			_ignoreEvent = true;
			Patients.Text = "";
			Protocols.Text = "";
			_ignoreEvent = false;
		}

		private void Patients_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (chkCombine.Checked)
				return;
			if (_ignoreEvent)
				return;

			_ignoreEvent = true;
			Tests.Text = "";
			Protocols.Text = "";
			_ignoreEvent = false;
		}
		#endregion selectedIndexChanged

		private void btnRun_Click(object sender, System.EventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			StringBuilder sql = new StringBuilder();
			int protocol;
			int testID;
			int patientID;

			sql.Append("SELECT t.ID, d.Protocol, d.Patient, " +
				" tt.Display, t.Location, t.NotUsed, t.NoShow,  " +
				" t.OutDate, t.OutTo, t.IsTestCheckOut, t.Result " +
				" FROM TestSamples t, DrawSamples d, TestType_L tt " +
				" WHERE t.DrawSample = d.ID " +
				" AND t.TestType = tt.ID");

			//SqlConnection conn = LoginForm.GetSqlConnection();
			_criteria = new StringBuilder();
			_criteria.Append("Criteria: ");
			if (Protocols.SelectedIndex > 0)
			{
				_criteria.Append("  Protocol = " + Protocols.Text);
				protocol = Convert.ToInt32(Protocols.Text);
				sql.Append(" AND d.Protocol =" + protocol);
			}
			if (Tests.SelectedIndex > 0)
			{
				_criteria.Append("  Test Type = " + Tests.Text);
				testID = ((NameVal)Tests.SelectedItem).Val;
				sql.Append(" AND t.TestType = " + testID);
			}
			if (Patients.SelectedIndex > 0)
			{
				_criteria.Append("  Patient = " + Patients.Text);
				patientID = ((NameVal)Patients.SelectedItem).Val;
				sql.Append(" AND d.Patient = " + patientID);
			}
			sql.Append(" ORDER BY t.ID");

			try
			{
				//DataSet ds = SqlHelper.ExecuteDataset(conn, CommandType.Text, sql.ToString());
				DataSet ds = DataAccess.GetDataSet(sql.ToString());
				_dataTable = ds.Tables[0];

				//get view
				StringBuilder filter = new StringBuilder();
				_dataView = new DataView(_dataTable);

				_resultsCriteria = new StringBuilder();
				_resultsCriteria.Append("Query Results Criteria:  ");
				if (!chkShowAll.Checked)
				{
					if (chkFreezer.Checked)
					{
						_resultsCriteria.Append("  In Freezer");
						filter.Append("Location IS NOT NULL");
					}

					if (chkTesting.Checked && !chkOutOther.Checked)
					{
						_resultsCriteria.Append("  Out For Testing");
						if (filter.Length > 0)
							filter.Append(" OR ");
						filter.Append("IsTestCheckOut = 1");
					}

					if (chkTesting.Checked && chkOutOther.Checked)
					{
						_resultsCriteria.Append("  Out For Testing  Out Other");
						if (filter.Length > 0)
							filter.Append(" OR ");
						filter.Append("OutDate IS NOT NULL");
					}

					if (chkOutOther.Checked && !chkTesting.Checked)
					{
						_resultsCriteria.Append("  Out Other");
						if (filter.Length > 0)
							filter.Append(" OR ");
						filter.Append("OutDate IS NOT NULL AND IsTestCheckOut <> 1");
					}
				}
				else
					_resultsCriteria.Append("  Show All");

				_dataView.RowFilter = filter.ToString();
				dGrd.DataSource = _dataView;
				if (this._dataView.Count > 0)
					btnPrint.Enabled = true;
				else
					btnPrint.Enabled = false;
			}
			catch (Exception ex)
			{
				//bool b = ////ExceptionPolicy.HandleException(ex, "Exception Policy");
				sb.Append("Could not run query.");
				sb.Append(Environment.NewLine);
				sb.Append("Error message: " + ex.Message);
				MessageBox.Show(this, sb.ToString(), "Query Failed", MessageBoxButtons.OK, MessageBoxIcon.Error);
			}
			finally
			{
				//if(conn != null)
				//    conn.Dispose();
			}
		}

		private void btnExit_Click(object sender, System.EventArgs e)
		{
			this.Close();
		}

		private void chkShowAll_CheckedChanged(object sender, System.EventArgs e)
		{
			if (chkShowAll.Checked)
			{
				chkFreezer.Checked = false;
				chkTesting.Checked = false;
				chkOutOther.Checked = false;
			}
		}

		private void chkOther_CheckedChanged(object sender, System.EventArgs e)
		{
			CheckBox chk = (CheckBox)sender;
			if (chk.Checked)
			{
				if (chkShowAll.Checked)
					chkShowAll.Checked = false;
			}
		}

		#region print stuff
		private void btnPrint_Click(object sender, System.EventArgs e)
		{
			Print_Report();
		}

		private void Print_Report()
		{
			StringBuilder sb = new StringBuilder();

			this._pDoc = new PrintDocument();
			this._pDoc.DefaultPageSettings.Landscape = true;
			this._pDlg = new PrintDialog();
			this._pDlg.Document = this._pDoc;

			if (this._pDlg.ShowDialog(this) == DialogResult.Cancel)
				return;

			Cursor.Current = Cursors.WaitCursor;
			this._pDoc.PrintPage += new PrintPageEventHandler(_pDoc_PrintPage);

			_page = 1;
			_startRow = 0;
			this._pDoc.Print();
			this._pDoc.PrintPage -= new PrintPageEventHandler(_pDoc_PrintPage);
		}

		private void _pDoc_PrintPage(object sender, PrintPageEventArgs e)
		{
			StringBuilder sb = new StringBuilder();
			Graphics gfx = e.Graphics;
			float pageBottom = gfx.VisibleClipBounds.Height;
			float pageWidth = gfx.VisibleClipBounds.Width;
			float leftMargin = 50;
			float topMargin = 50;

			Font prntFont = new Font("Arial", 10);
			Font titleFont = new Font("Arial", 14, FontStyle.Bold);
			Font subTitleFont = new Font("Arial", 12);
			Font ColumnHeadFont = new Font("Arial", 10, FontStyle.Bold);

			Pen pen = new Pen(Color.Black);

			//get the line height with some padding
			float lineHeight = prntFont.GetHeight(e.Graphics) + 2;

			//set the drawing to the top left of the page
			float yPos = topMargin;
			float xPos = leftMargin;

			//print page #
			string page = "Page " + this._page;
			PrintingUtils.PrintCenter(page, e, prntFont, pageBottom - lineHeight);

			//print title and subtitle
			if (this._page == 1)
			{
				PrintingUtils.PrintCenter("Core Lab - Inventory Query Report", e, titleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				PrintingUtils.PrintCenter(this._criteria.ToString(), e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				PrintingUtils.PrintCenter(this._resultsCriteria.ToString(), e, subTitleFont, yPos);
				yPos += titleFont.GetHeight(e.Graphics) + 2;
				sb.Append("Date: " + DateTime.Today.ToShortDateString());
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			else
			{
				sb.Append("Core Lab - Inventory Query Report - ");
				sb.Append("Date: " + DateTime.Today.ToShortDateString());
				sb.Append("  continued");
				PrintingUtils.PrintCenter(sb.ToString(), e, subTitleFont, yPos);
				yPos += subTitleFont.GetHeight(e.Graphics) + 2;
			}
			yPos += lineHeight;

			//print heading
			float c1 = 25;  //75
			float c2 = 100; //75
			float c3 = 175; //125			
			float c4 = 300; //150
			float c5 = 450; //150			
			float c6 = 600; //100
			float c7 = 700; //125
			float c8 = 825; //75
			float c9 = 900; //

			float c1W = 75;  //id
			float c2W = 75;  //spid
			float c3W = 125; //patient
			float c4W = 150; //test 
			float c5W = 150; //location
			float c6W = 100; //OutDate			
			float c7W = 125; //OutTo
			float c8W = 75;  //In House
			float c9W = 100; //Result

			RectangleF rec = new RectangleF();

			gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
			gfx.FillRectangle(Brushes.LightBlue, 23, yPos, pageWidth - 48, lineHeight);

			PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
			gfx.DrawString("Test ID", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
			gfx.DrawString("SPID", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
			gfx.DrawString("Patient", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
			gfx.DrawString("Test Type", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
			gfx.DrawString("Location", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
			gfx.DrawString("Out Date", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7W);
			gfx.DrawString("Out To", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8W);
			gfx.DrawString("In House", ColumnHeadFont, Brushes.Black, rec);

			PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9W);
			gfx.DrawString("Result", ColumnHeadFont, Brushes.Black, rec);
			yPos += lineHeight;

			lineHeight = prntFont.GetHeight(e.Graphics) + 18;
			//get the number of lines we can print
			int maxLines = (int)Math.Ceiling((double)((pageBottom - yPos) / lineHeight));
			maxLines -= 2;
			int curLine = 0;

			StringFormat fmt = new StringFormat();
			fmt.Trimming = StringTrimming.EllipsisCharacter;

			DataRowView drv;
			//string patient;
			string location = "";
			string val = "";
			int spid = 0;
			DateTime dt;
			for (int row = _startRow; row < this._dataView.Count; row++)
			{
				if (curLine == maxLines)
				{
					_startRow = row;
					this._page++;
					e.HasMorePages = true;
					return;
				}

				drv = this._dataView[row];

				val = drv["ID"].ToString();
				PrintingUtils.SetRectangle(ref rec, c1, yPos, lineHeight, c1W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				spid = (int)drv["SPID"];
				PrintingUtils.SetRectangle(ref rec, c2, yPos, lineHeight, c2W);
				gfx.DrawString(spid.ToString("0000"), prntFont, Brushes.Black, rec, fmt);

				val = drv["Patient"].ToString();
				PrintingUtils.SetRectangle(ref rec, c3, yPos, lineHeight, c3W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				val = drv["Display"].ToString();
				PrintingUtils.SetRectangle(ref rec, c4, yPos, lineHeight, c4W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				location = "";
				val = drv["Location"].ToString();
				if (val.Length > 0)
					location = val;
				else
				{
					val = drv["NotUsed"].ToString();
					if (val == "True")
						location = "Not Used";
					val = drv["NoShow"].ToString();
					if (val == "True")
						location = "No Show";
				}
				PrintingUtils.SetRectangle(ref rec, c5, yPos, lineHeight, c5W);
				gfx.DrawString(location, prntFont, Brushes.Black, rec);

				val = drv["OutDate"].ToString();
				if (val.Length > 0)
				{
					dt = Convert.ToDateTime(val);
					val = dt.ToShortDateString();
				}
				PrintingUtils.SetRectangle(ref rec, c6, yPos, lineHeight, c6W);
				gfx.DrawString(val, prntFont, Brushes.Black, rec, fmt);

				val = drv["OutTo"].ToString();
				PrintingUtils.SetRectangle(ref rec, c7, yPos, lineHeight, c7);
				gfx.DrawString(val, prntFont, Brushes.Black, rec);

				val = drv["IsTestCheckOut"].ToString();
				if (val == "True")
					val = "Yes";
				else
					val = "";
				PrintingUtils.SetRectangle(ref rec, c8, yPos, lineHeight, c8);
				gfx.DrawString(val, prntFont, Brushes.Black, rec);

				val = drv["Result"].ToString();
				PrintingUtils.SetRectangle(ref rec, c9, yPos, lineHeight, c9);
				gfx.DrawString(val, prntFont, Brushes.Black, rec);

				gfx.DrawRectangle(Pens.Black, 23, yPos, (pageWidth - 48), lineHeight);
				yPos += lineHeight;
				curLine++;
			}
		}
		#endregion print stuff

		private void btnGrid_Click(object sender, System.EventArgs e)
		{
			FormDockingManager fdm = _main.DockManager;

			if (this._fg != null)
			{
				//if its not null then we have already been thru here
				//so just make sure the grid is the active one
				fdm.ActivateDockControl(this._formInfo.TableName);
				return;
			}

			//does the grid exist
			if (fdm.DockControlExists(this._formInfo.TableName))
			{
				//need to get a reference to the formGrid
				_fg = (FormGrid)fdm.GetDockControl(this._formInfo.TableName);
				//make sure it is visible
				if (!fdm.IsDockControlVisible(this._formInfo.TableName))
					fdm.SetDockControlVisibility(this._formInfo.TableName, true);
				//then activate it
				fdm.ActivateDockControl(this._formInfo.TableName);
			}
			else //create it		
			{
				_fg = new FormGrid("SELECT * FROM " + this._formInfo.TableName, this, this._formInfo.TableName);
				_fg.Text = this._formInfo.TableName;
				BLGridViewEventArgs ea = new BLGridViewEventArgs(this._formInfo.TableName, _fg);

				if (GridView != null)
					GridView(this, ea);
				_fg.Show();
			}
			//this is used to set the grid reference to null
			_fg.Closing += new CancelEventHandler(_fg_Closing);
		}

		private void _fg_Closing(object sender, CancelEventArgs e)
		{
			_fg = null;
		}


	}
}

